import React, { useState } from "react";
import { Editor } from "@tinymce/tinymce-react";

const FullRichTextEditor = ({ initialContent = "", onContentChange }) => {
  // 存储编辑器实例
  let editorInstance = null;
  // 存储编辑器内容
  const [content, setContent] = useState(initialContent);
  console.log(content);
  // 初始化编辑器实例
  const handleInit = (evt, editor) => {
    editorInstance = editor;
    console.log("编辑器初始化完成");
  };

  // 内容变化时触发
  const handleEditorChange = (newContent) => {
    setContent(newContent);
    if (onContentChange) {
      onContentChange(newContent); // 对外暴露内容变化回调
    }
  };

  // 编辑器 API 方法封装
  const editorApi = {
    // 获取HTML内容
    getHtmlContent: () => {
      return editorInstance ? editorInstance.getContent() : "";
    },
    // 获取纯文本内容
    getTextContent: () => {
      return editorInstance
        ? editorInstance.getContent({ format: "text" })
        : "";
    },
    // 设置内容
    setContent: (html) => {
      if (editorInstance) {
        editorInstance.setContent(html);
      }
    },
    // 清空内容
    clearContent: () => {
      if (editorInstance) {
        editorInstance.setContent("");
      }
    },
    // 撤销操作
    undo: () => {
      if (editorInstance) {
        editorInstance.undoManager.undo();
      }
    },
    // 重做操作
    redo: () => {
      if (editorInstance) {
        editorInstance.undoManager.redo();
      }
    },
    // 插入图片
    insertImage: (url, alt = "图片") => {
      if (editorInstance) {
        editorInstance.execCommand(
          "mceInsertContent",
          false,
          `<img src="${url}" alt="${alt}" />`
        );
      }
    },
    // 插入链接
    insertLink: (url, text = "链接") => {
      if (editorInstance) {
        editorInstance.execCommand("mceInsertLink", false, { href: url, text });
      }
    },
  };

  // 示例：外部调用API的方法
  const handleApiDemo = () => {
    console.log("HTML内容:", editorApi.getHtmlContent());
    console.log("纯文本内容:", editorApi.getTextContent());
    // 示例：插入一张图片
    editorApi.insertImage("https://picsum.photos/400/300", "示例图片");
  };

  return (
    <div className="rich-editor-container" style={{ margin: "20px" }}>
      <Editor
        apiKey="1ljtdmeo69fwvbae7f5yiavqogs77qe4ryrq6m3a0bcnqvw6" // 本地开发使用，生产环境需到官网申请
        initialValue={initialContent}
        init={{
          // 基础配置
          height: 500,
          width: "100%",
          language: "zh-CN", // 中文语言（需配置语言包）
          directionality: "ltr", // 文本方向
          browser_spellcheck: true, // 启用浏览器拼写检查
          resize: "both", // 允许调整大小
          statusbar: true, // 显示状态栏
          menubar: true, // 显示菜单栏

          // 插件配置（功能模块）
          plugins:
            "advlist autolink lists link image charmap print preview " +
            "searchreplace visualblocks code fullscreen " +
            "insertdatetime media table paste help wordcount " +
            "save codesample emoticons hr pagebreak",
          // 工具栏配置（按组划分）
          toolbar: `
            undo redo | formatselect | fontselect fontsizeselect |
            bold italic underline strikethrough forecolor backcolor |
            alignleft aligncenter alignright alignjustify |
            bullist numlist outdent indent | link image media |
            table codesample emoticons | hr pagebreak removeformat |
            preview fullscreen code help
          `,

          // 进阶配置
          importcss_append: true, // 导入页面CSS
          templates: [
            { title: "标题模板", content: "<h1>新标题</h1><p>内容...</p>" },
            {
              title: "列表模板",
              content: "<ul><li>项目1</li><li>项目2</li></ul>",
            },
          ],
          image_advtab: true, // 图片高级选项卡
          codesample_languages: [
            { text: "JavaScript", value: "javascript" },
            { text: "HTML/XML", value: "markup" },
            { text: "CSS", value: "css" },
            { text: "React", value: "jsx" },
          ],
          media_live_embeds: true, // 媒体实时预览
          paste_data_images: true, // 允许粘贴图片
          quickbars_selection_toolbar:
            "bold italic | quicklink h2 h3 blockquote", // 选中时显示的快速工具栏
          noneditable_noneditable_class: "mceNonEditable", // 不可编辑内容的类名
          toolbar_mode: "sliding", // 工具栏溢出时滑动显示

          // 图片上传配置（需后端接口支持）
          images_upload_url: "/api/upload-image", // 图片上传接口
          images_upload_handler: (blobInfo, success, failure) => {
            // 自定义图片上传逻辑
            const formData = new FormData();
            formData.append("file", blobInfo.blob(), blobInfo.filename());

            fetch("/api/upload-image", {
              method: "POST",
              body: formData,
            })
              .then((response) => response.json())
              .then((data) => {
                success(data.url); // 上传成功后返回图片URL
              })
              .catch((error) => {
                failure("上传失败: " + error.message);
              });
          },
        }}
        onInit={handleInit}
        onEditorChange={handleEditorChange}
      />

      {/* 操作按钮示例 */}
      <div style={{ marginTop: "15px", display: "flex", gap: "10px" }}>
        <button onClick={editorApi.clearContent} style={buttonStyle}>
          清空内容
        </button>
        <button onClick={editorApi.undo} style={buttonStyle}>
          撤销
        </button>
        <button onClick={editorApi.redo} style={buttonStyle}>
          重做
        </button>
        <button onClick={handleApiDemo} style={buttonStyle}>
          API 演示
        </button>
      </div>
    </div>
  );
};

// 按钮样式
const buttonStyle = {
  padding: "6px 12px",
  border: "1px solid #ccc",
  borderRadius: "4px",
  cursor: "pointer",
  backgroundColor: "#fff",
  fontSize: "14px",
};

export default FullRichTextEditor;
